<template>
  <panel title="最近7天服务异常统计">
    <div class="ml20 mr20">
      <x-row v-show="show">
        <x-col :span="24">
          <Bar :width="chartWidth" :height="chartHeight" :options="trendOptions"></Bar>
        </x-col>
      </x-row>
    </div>
  </panel>
</template>

<script>
import PRODUCT_IDS from 'config/product-ids'
import DEVICE_TYPES from 'config/device-types'
import formatDate from 'filters/format-date'
import { patchLostDates } from 'utils'
import api from 'api'
import _ from 'lodash'

let phaseProductId = PRODUCT_IDS[DEVICE_TYPES.PHASE]
let ruleTag = '严重'
let endTime = new Date()
let startTime = new Date(endTime - 6 * 24 * 3600 * 1000)
let beginDay = formatDate(startTime, 'yyyy-MM-dd', true)
let beginHour = 0
let endDay = formatDate(endTime, 'yyyy-MM-dd', true)
let endHour = 24

export default {
  name: 'alertHistory',

  data () {
    return {
      show: false,
      chartWidth: '400px',
      chartHeight: '230px',
      trend: {
        xAxis: [],
        series: []
      },
      alertCount: [],
      alertFactorCount: []
    }
  },

  computed: {
    alert () {
      // 对返回来的数据进行排序
      return _.clone(_.sortBy(this.alertCount, function (o) { return o.day }))
    },
    alertFactor () {
      // 对返回来的数据进行排序
      return _.clone(_.sortBy(this.alertFactorCount, function (o) { return o.day }))
    },
    // 趋势图表配置
    trendOptions () {
      let _self = this
      let arr = []
      let arrFactor = []
      _self.alert.forEach((item) => {
        arr.push(item.count)
      })
      _self.alertFactor.forEach((item) => {
        arrFactor.push(item.count)
      })
      return {
        tooltip: {
          trigger: ['axis', 'item'],
          formatter: '{b} <br/>{a}: {c}'
        },
        grid: {
          containLabel: true,
          left: '3%',
          right: '5%',
          bottom: '10%',
          top: '15%'
        },
        legend: {
          data: [
            {
              name: '总功率因数异常告警',
              icon: 'circle'
            },
            {
              name: '总有功功率异常报警',
              icon: 'circle'
            }
          ],
          align: 'left',
          right: 0,
          top: 0,
          orient: 'horizontal',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: this.trend.xAxis
        }],
        yAxis: [{
          type: 'value'
        }],
        series: [{
          name: '总有功功率异常报警',
          type: 'line',
          stack: '总有功功率异常报警',
          data: arr
        }, {
          name: '总功率因数异常告警',
          type: 'line',
          stack: '总功率因数异常告警',
          data: arrFactor
        }]
      }
    }
  },

  created () {
    this.requestRestfulData()
    this.initialize()
    this.list()
  },

  methods: {
    initialize () {
      setTimeout(() => {
        this.chartWidth = `${(this.$el.clientWidth - 40)}px`
        this.chartHeight = `${this.$el.clientHeight - 31}px`
        this.show = true
      }, 0)
    },
    list () {
      let macArr = []
      switch (this.$route.path.split('/')[1]) {
        case ':0':
          // 8F8DD9699983 1栋2 7F5DB1EAF401 1栋1 5CAB498C7CB6 13spe
          macArr = ['719801F4A59D', '4AC3CDB84B92', '3A212337CCF1', 'C7E8A35FA8FC', 'DC8178501503', '9D285119036B', 'B784D681E687', '2C04CE412723', '96F9EC737A1E', '45F2F4A1CC8E', '94E9FEE303F1', 'C138E8A23A12', '5A3B10F54A60', 'D1F99240517E', '8A6002ED6624', 'CB2D6E742EFF', 'E435BD144118', 'E6F3267998F5', '0CE58B1C9934', 'B9181FAB2899', 'B9E026DDC876', 'E98185D64CCC', '7574D4C83C97', '7F5DB1EAF401', '8F8DD9699983', '5CAB498C7CB6']
          break
        case ':1':
          macArr = ['A895A2F9DD57', '34C6D27BB997', 'B186085F58CF', '6C892622F336']
          break
        case ':2':
          break
        case ':3':
          break
      }
      let _self = this
      for (let i = 0; i < 7; i++) {
        let params = {
          'query': {
            'create_date': {
              '$gte': new Date(new Date(endDay) - 1000 * 60 * 60 * 24 * (i + 1)),
              '$lte': new Date(new Date(endDay) - 1000 * 60 * 60 * 24 * i)
            },
            'content': {
              '$in': ['总有功功率异常报警']
            },
            'mac': {
              '$in': macArr
            }
          }
        }
        api.alert.getAlerts(params).then((res) => {
          let obj = {
            'day': formatDate(new Date(new Date(endDay) - 1000 * 60 * 60 * 24 * i), 'MM-dd', true),
            'count': res.data.count
          }
          _self.alertCount.push(obj)
        }).catch((err) => {
          this.handleError(err)
        })
        params['query']['content']['$in'][0] = '总功率因数异常告警'
        api.alert.getAlerts(params).then((res) => {
          let obj = {
            'day': formatDate(new Date(new Date(endDay) - 1000 * 60 * 60 * 24 * i), 'MM-dd', true),
            'count': res.data.count
          }
          _self.alertFactorCount.push(obj)
        }).catch((err) => {
          console.log(err)
          this.handleError(err)
        })
      }
    },

    /**
     * 获取告警趋势图表数据
     */
    requestRestfulData () {
      let xAxis = []
      this.trend.series = []

      let rules = [
        {
          id: '280fa6b1994c4a00',
          name: '总功率因数异常告警'
        },
        {
          id: '280fa6b1a1353200',
          name: '总有功功率异常报警'
        }
      ]
      rules.forEach((rule) => {
        api.statistics.getTagRuleTrend(phaseProductId, ruleTag, rule.id, beginDay, endDay, beginHour, endHour).then((res) => {
          if (res.status !== 200) {
            return
          }
          let data = res.data.map((item) => {
            // 算出某天告警总数
            let sum = _.sum(_.map(item.hours, 'message'))
            return {
              day: item.day,
              value: sum
            }
          })
          data = patchLostDates(data, beginDay, endDay, ['value'])
          if (!xAxis.length) {
            xAxis = _.map(data, 'day')
            xAxis = xAxis.map((item) => formatDate(item, 'MM-dd'))
          }
          // this.trend.series.push({
          //   name: rule.name,
          //   type: 'line',
          //   stack: rule.name,
          //   data: _.map(data, 'value')
          // })
          this.trend.xAxis = xAxis
        }).catch((res) => {
          this.handleError(res)
        })
      })
    }
  }
}
</script>
